package blog.web.file.action;

import blog.sys.entity.SysFile;
import blog.sys.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import pub.functions.FsFuncs;
import pub.functions.ReqFuncs;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by zzl on 2015/11/1.
 */
@Controller
public class GetAction {

	@RequestMapping
	public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Integer id = ReqFuncs.getIntegerParam(request, "id");
		boolean download = request.getParameter("download") != null;

		ServletContext servletContext = request.getSession().getServletContext();
		String sysFileDir = servletContext.getRealPath("/sysfile");
		String SEP = File.separator;
		//
		File fileDir = new File(sysFileDir + SEP + id);
		String[] fileNames = fileDir.list();
		String fileName;
        String contentType = null;
		if (fileNames == null || fileNames.length == 0) {
			fileDir.mkdirs();
			SysFile sysFile = sysFileService.get(id);
			if (sysFile == null) {
				return;
			}
            contentType = sysFile.getContentType();
			fileName = FsFuncs.getFileName(sysFile.getName());

            String localFileName = "file";
            int lastDotPos = fileName.lastIndexOf('.');
            if(lastDotPos != -1) {
                localFileName += fileName.substring(lastDotPos);
            }
            //
            fileName = localFileName;

			File file = new File(fileDir.getAbsolutePath() + SEP + fileName);
			OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
			os.write(sysFile.getContent());
			os.close();
		}
		else {
			fileName = fileNames[0];
		}

		if (download) {
			String attachmentName = new String(fileName.getBytes("GB2312"), "iso8859-1");
			response.setHeader("Content-disposition", "attachment; filename=" + attachmentName);
			response.setContentType("application/x-download");
		}
		else {
			String attachmentName = new String(fileName.getBytes("GB2312"), "iso8859-1");
			response.setHeader("Content-disposition", "inline; filename=" + attachmentName);
//			response.setContentType("application/octet-stream");
            response.setContentType(contentType);
		}
		String filePath = "/sysfile/" + id + "/" + fileName;
		servletContext.getRequestDispatcher(filePath).forward(request, response);
//        RequestDispatcher rd = request.getServletContext().getNamedDispatcher("default");
	}

	@Autowired
	private SysFileService sysFileService;
}
